package com.gxa.ehome.web.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.ehome.entity.UserBase;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.service.UserServiceBase;
import com.gxa.ehome.service.impl.UserServiceBaseImpl;
import com.gxa.ehome.util.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//servlet上通过.do让过滤器匹配,好处
@WebServlet(name = "UserServlet",urlPatterns = "/user.do")
public class UserServletBase extends HttpServlet {

   private UserServiceBase userServiceBase =new UserServiceBaseImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 处理请求中的中文, 使用UTF-8编码
        request.setCharacterEncoding("UTF-8");
        String code=null;
        String msg=null;
        String data = "{}";
        JsonResult jsonResult = new JsonResult();
        // 先获取前端传递的参数

        //获取前端请求头数据
//        String method2 = request.getHeader("method2");
//        System.out.println("method2:"+method2);

        //获取操作的类型: method
//        String method = request.getParameter("method");
        String method = request.getHeader("method");
        //自定义请求头
        switch (method) {
            case "login": {
                String username= request.getParameter("username");
                String pwd= request.getParameter("pwd");
//                System.out.println("username:" + username);
//                System.out.println("pwd:" + pwd);
//            System.out.println("123");
                UserBase louser=null;
                try {
                    louser = userServiceBase.login(username, pwd);
                    if (louser!=null){
//                        code="1";
//                        msg="登录成功";
//                        String name=louser.getUsername();
//                        data = "{\"name\":\""+louser.getName()+"\"}";
                        jsonResult.setCode("1");
                        jsonResult.setMsg("登录成功,欢迎回来,"+louser.getName());
                    }else {
                        jsonResult.setCode("0");
                        jsonResult.setMsg("登录失败");
//                        code="0";
//                        msg="登录失败";
                    }
//            System.out.println(login);
                } catch (Exception e) {
                    //  e.printStackTrace();
                    // 出现异常, 且是一个业务异常类型,就给前端返回失败的信息; 否则记录日志(暂时先打印在控制台)
//                    code = "0";
                    jsonResult.setCode("0");

                    if(e instanceof BusinessException){
                        jsonResult.setMsg(e.getMessage());
//                        msg = e.getMessage();
                    }else{
                        e.printStackTrace();   // 将来要改为记录日志操作
                    }
                }
                break;
            }
            case "register": {
                // 获取前端传递的参数
//                String username = request.getParameter("username");
//                String name = request.getParameter("name");
//                String pwd = request.getParameter("pwd");
                BufferedReader reader = request.getReader();
                StringBuilder builder = new StringBuilder();
                String line=null;
                while ((line=reader.readLine())!=null){
                    builder.append(line);
                }
                reader.close();

                //把参数部分注入到一个User对象上
                UserBase user = JSON.parseObject(builder.toString(), UserBase.class);
//                System.out.println(user);
//                User user = new User(username, MD5Util.encode(pwd),name);
                try {
                    // 调用自定义的register方法,完成UserService中的register调用
                    UserBase register = userServiceBase.register(user);
                    // 加工处理返回给前端的数据

                    if (register!=null){
                        jsonResult.setCode("1");
                        jsonResult.setMsg("注册成功,您的编号是,"+register.getId());
                    }
//                    code= "1";
//                    msg = "";
//                    data = "{\"id\":\""+register.getId()+"\"}";
                } catch (Exception e) {
                    // 获取BusinessException中的消息
//                    code= "0";
                    jsonResult.setCode("0");

                    if(e instanceof BusinessException){
                        // 如果是业务异常类型, 就把msg返回给前端显示
//                        msg = e.getMessage();
                        jsonResult.setMsg(e.getMessage());
                    }else{
                        e.printStackTrace();
                    }
                }
                break;
            }
            case "selectAllByPage": {
                Integer page = Integer.parseInt(request.getParameter("page"));
                Integer size = Integer.parseInt(request.getParameter("size"));
                try {
                    List<UserBase> users = userServiceBase.selectAllByPage(page, size);
                    //  code = "1";
                    //   msg = "";
                    //   data = JSON.toJSONString(users);  // ["",]
                    // 先把要返回的数据注入JsonResult对象中
                    jsonResult.setCode("1");
                    jsonResult.setData(users);
                } catch (Exception e) {
                    jsonResult.setCode("0");
                    jsonResult.setMsg("没有数据");
                }
//                data = [{username:"",name:"",id:""},{username:"",name:"",id:""}]
                //FastJson alibaba 使用
                // 1. 下载  从https://mvnrepository.com/ 搜索
                // 2. 引入到当前工程中
                // add as Library: 本地用
                // 放在WEB-INF下的lib下是部署到服务器中能识别
                //3. 在JUnit测试用例中测试使用
                break;
            }
            case "deleteById":{
                String uid = request.getParameter("uid");
                try {
                    Integer integer = userServiceBase.deleteById(Integer.parseInt(uid));
                    if(integer==1){
                        jsonResult.setCode("1");
                        jsonResult.setMsg("删除成功");
                    }else{
                        jsonResult.setCode("0");
                        jsonResult.setMsg("删除失败,请检查id");
                       /* BusinessException businessException = new BusinessException("删除失败,请检查id");
                        request.setAttribute("e",businessException);
                        // 统一交给ExceptionHandlerServlet处理
                        this.getServletContext().getRequestDispatcher("/exception").forward(request,response)*/;
                    }
                } catch (Exception e) {
                    jsonResult.setCode("0");
                    jsonResult.setMsg("系统发送未知错误,请稍后再试");
                }
                break;
            }
            case "update":{
                String uid = request.getParameter("uid");
                String name = request.getParameter("name");
                String pwd = request.getParameter("pwd");
                //String username = request.getParameter("username");  用户名,花钱修改
                //生成一个组装了所有修改字段值的对象
                UserBase user = new UserBase();
                user.setName(name);
                user.setPwd(pwd);
                try {
                    userServiceBase.update(Integer.parseInt(uid),user);
                    jsonResult.setCode("1");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            default:
                break;
        }
        // 调用业务方法完成登录操作(service : UserService)
        // 封装返回给前端的综合数据(code/msg/data : json)
        // response.getOutputStream();  字节流
//        / 如果在服务器中表示: localhost:8080/ApplicationContextName
//         / 如果在浏览器中: localhost:8080
        // 响应对象处理中文字符
        response.setCharacterEncoding("UTF-8");   // 服务器端的字符集设置(影响流)- java代码相关
        response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 浏览器行为
        PrintWriter writer = response.getWriter();
        // 返回一个文本
//        writer.print("你好,欢迎来到我的世界");
        // 返回jsonString
        //  writer.print("{\"name\":\"张三丰\"}");
//        String result = "{\"code\":"+code+",\"msg\":\""+msg+"\",\"data\":"+data+"}";
//        System.out.println(result);
//        writer.print(result);
//        writer.flush();
//        writer.close();
        String s = JSON.toJSONString(jsonResult);
        writer.print(s);
        writer.flush();
        writer.close();
        //下面这个是封装的上面的操作,流的传输
//        ResponseUtil.send(response,s);


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // alt+enter: 纠错
//    public User login(String username, String pwd) {
//
//        return null;
//    }
}
